// 原组件文件
import { defineComponent, onMounted, onUnmounted, ref, computed } from 'vue';
import Style from "./1080.module.scss";
// 导入图片（保持不变）
import Image14 from '@/assets/images/14.png';
import Image12 from '@/assets/images/12.png';
// ... 其他图片导入
import yellowImg from '@/assets/images/15.png';
import blueImg from '@/assets/images/11.png';
import ImageDy from '@/assets/images/dy.png';
import Image6 from '@/assets/images/6.png';
import lanseMin from '@/assets/images/2.png';
import lanseicon from '@/assets/images/1.png';
import { useRouter } from 'vue-router';
import { KEEP_VIDEO_TOP } from '~/src/config';
import { getMzjf } from "@/api/his";
import { IHomePageTitle, IRouter } from "@/api/typing";
// 导入Pinia存储
import { useTitleStore } from '@/store/modules/homeTitle';
import {useBreadcrumbStore} from "@/store/modules/breadcrumb";
import {useCardStore} from "@/store/modules/readCard";

export default defineComponent({
    setup() {
        const router = useRouter();
        const titleStore = useTitleStore();

        // 哈希值逻辑（保持不变）
        const fetchHashValue = async () => {
            // ... 原逻辑不变
        };

        let timmer: any = null;
        onMounted(() => {
            timmer = setInterval(() => fetchHashValue(), 10000);
            // 触发Pinia请求数据（仅首次）
            titleStore.fetchRawData();
        });

        onUnmounted(() => {
            clearInterval(timmer);
        });

        // 核心：处理数据格式化（在组件中实现）
        const formatTitleData = (sourceData: any) => {
            // 1. 确定使用的数据源：接口数据为空则用基础数据
            // const useBaseData = !sourceData.titleMax || !sourceData.titleMax || sourceData.titleMax.length === 0;
            // const dataSource = useBaseData ? titleStore.baseTitle : sourceData.rows[0];


            // 2. 处理大标题
            let max = (sourceData.titleMax?.length || 0) > 0 ? sourceData.titleMax : titleStore.baseTitle.titleMax;
            max = max
                .filter((item: IHomePageTitle) => item.is_show)
                .map((item: IHomePageTitle) => {
                    const key = item.to as keyof typeof IRouter;
                    const toValue = IRouter.hasOwnProperty(key) ? IRouter[key] : null;
                    return { ...item, to: toValue };
                });

            // 拆分大标题（前3个 + 更多）
            let titleMax: IHomePageTitle[] = [];
            let titleMoreMax: IHomePageTitle[] = [];
            if (max.length > 4) {
                titleMax = max.slice(0, 3);
                titleMoreMax = max.slice(3);
                titleMax.push({
                    title: '更多',
                    desc: '',
                    img: yellowImg,
                    icon: Image6,
                    is_show: true,
                    to: '/moreTitle',
                    data: titleMoreMax
                });
            } else {
                titleMax = max;
            }

            // 3. 处理小标题
            let min: any = (sourceData.titleMin?.length || 0)> 0 ? sourceData.titleMin : titleStore.baseTitle.titleMin;
            min = min
                .filter((item: IHomePageTitle) => item.is_show)
                .map((item: IHomePageTitle) => {
                    const key = item.to as keyof typeof IRouter;
                    const toValue = IRouter.hasOwnProperty(key) ? IRouter[key] : null;
                    return { ...item, to: toValue };
                });

            // 拆分小标题（前3个 + 更多）
            let titleMin: IHomePageTitle[] = [];
            let titleMoreMin: IHomePageTitle[] = [];
            if (min.length > 4) {
                titleMin = min.slice(0, 3);
                titleMoreMin = min.slice(3);
                titleMin.push({
                    title: '更多',
                    desc: '',
                    img: lanseMin,
                    iconImg:lanseicon,
                    icon: Image6,
                    is_show: true,
                    to: '/moreTitle',
                    data: titleMoreMin
                });
            } else {
                titleMin = min;
            }

            return { titleMax, titleMoreMax, titleMin, titleMoreMin };
        };

        // 计算属性：根据Pinia中的原始数据动态生成格式化后的数据
        const formattedData = computed(() => {
            // 只有当数据加载完成后才格式化
            if (!titleStore.isLoaded) return {
                titleMax: [],
                titleMoreMax: [],
                titleMin: [],
                titleMoreMin: []
            };
            // 使用接口原始数据进行格式化（内部会判断是否用基础数据）
            return formatTitleData(titleStore.rawData);
        });
         const breadcrumbStore =useBreadcrumbStore();
         const useTitle =useCardStore()
        // 点击事件（保持不变）
        const handleClick = (item: IHomePageTitle) => {
            if (item.to) {
                // 添加用户进入功能标题
                useTitle.setUsertitle(item?.title)
                //添加steps步骤条功能
                switch (item.title) {
                    case '挂号':breadcrumbStore.setghlx('挂号');break;
                    case '预约':breadcrumbStore.setghlx('预约');break;
                    case '门诊缴费':breadcrumbStore.setghlx('门诊缴费');break;
                    case '住院预交金':breadcrumbStore.setghlx('住院预交金');break;
                    case '取号':breadcrumbStore.setghlx('取号');break;
                }
                router.push({
                    path: item.to,
                    query: { itemInfo: JSON.stringify(item?.data) }
                });
            }
        };

        return () => (
            <>
                {!KEEP_VIDEO_TOP ? (
                    <div class={Style.video}>
                        <div class={Style.video_pad}>
                            <video
                                class="vid"
                                style={{ width: '100%', height: '100%' }}
                                id="video"
                                src="http://ld.zjldsoft.com:80/ldzzj/ldzzj/api?code=env.vedio&_t="
                                autoplay="true"
                                loop
                                muted
                            ></video>
                        </div>
                    </div>
                ) : ("")}

                <div class={Style.content_mar}>
                    <div class={Style.content}>
                        {/* 大标题：使用格式化后的数据 */}
                        {formattedData.value.titleMax.map((item, index) => (
                            <div
                                class={Style.item}
                                style={{ backgroundImage: `url(${item.img})` }}
                                onClick={() => handleClick(item)}
                                key={index}
                            >
                                <div>
                                    <div class={Style.text1}>{item.title}</div>
                                    <div class={Style.text2}>{item.desc}</div>
                                </div>
                                <img class={Style.item_icon} src={item.icon} />
                            </div>
                        ))}

                        {/* 小标题：使用格式化后的数据 */}
                        <div class={Style.min_content}>
                            {formattedData.value.titleMin.map((item, index) => (
                                <div
                                    class={Style.min_item}
                                    style={{ backgroundImage: `url(${item.img})` }}
                                    onClick={() => handleClick(item)}
                                    key={index}
                                >
                                    <div class={[Style.min_img]} style={{ backgroundImage: `url(${item.iconImg})` }}>
                                        <img class={Style.min_icon} src={item.icon} />
                                    </div>
                                    <div class={Style.min_item_text}>{item.title}</div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </>
        );
    }
});
